package 中国.杨森.实验室.jpa;

import java.time.LocalDateTime;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class 多库操作
{
	EntityManagerFactory emf1;
	EntityManager em1;
	EntityTransaction et1;

	EntityManagerFactory emf2;
	EntityManager em2;
	EntityTransaction et2;

	@Before
	public void 启动1()
	{
		emf1 = Persistence.createEntityManagerFactory("测试");
		em1 = emf1.createEntityManager();
		et1 = em1.getTransaction();
		et1.begin();
	}

	@After
	public void 关闭1()
	{
		et1.commit();
		em1.close();
		emf1.close();
	}

	@Before
	public void 启动2()
	{
		emf2 = Persistence.createEntityManagerFactory("测试2");
		em2 = emf2.createEntityManager();
		et2 = em2.getTransaction();
		et2.begin();
	}

	@After
	public void 关闭2()
	{
		et2.commit();
		em2.close();
		emf2.close();
	}

	protected void 关闭事务1()
	{
		et1.commit();
		em1.close();
		System.out.println("事物1关闭-----------");
	}

	protected void 开启事务1()
	{
		em1 = emf1.createEntityManager();
		et1 = em1.getTransaction();
		et1.begin();
		System.out.println("事物1开启-----------");
	}

	@Test
	public void 增删()
	{
		for (int i = 0; i < 5; i++)
		{
			学生 xs = new 学生();
			xs.set姓名("学生" + i);
			xs.set年龄((short) i);
			xs.set创建时间(LocalDateTime.now());
			em1.persist(xs);
		}

		关闭事务1();
		开启事务1();

		学生 xs = em1.find(学生.class, 2);

		学生 xs2 = new 学生();
		xs2.set姓名(xs.get姓名());
		xs2.set年龄(xs.get年龄());
		xs2.set创建时间(xs.get创建时间());
		em2.persist(xs2);
	}
}